#include "RePlugin.h"
#include "canvas/CanvasHandler.h"
#include "canvas/CanvasToolBarModel.h"
#include "canvas/FigureMap.h"

#include <QDebug>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QMutex>

void registerTypes()
{
    qmlRegisterType<CanvasToolType>("CanvasToolType", 1, 0, "CanvasToolType");
    qmlRegisterSingletonInstance("FigureMap", 1, 0, "FigureMap", FigureMap::instance());
    qmlRegisterSingletonInstance("CanvasHandler", 1, 0, "CanvasHandler", CanvasHandler::instance());
    qmlRegisterSingletonInstance("CanvasToolBarModel", 1, 0, "CanvasToolBarModel", CanvasToolBarModel::instance());
}

void RenderEngine::registerTypes(const char *uri)
{
    Q_INIT_RESOURCE(ReEngine);
    // @uri
    qmlRegisterType<RenderEngine>(uri, 1, 0, "RenderEngine");
    ::registerTypes();
}

static PluginInfo  *info;

void releasePluginInfo()
{
    delete info->m_subWin;
    delete info->m_chiBtn;
    delete info;
}

PluginInfo *getPluginInfo(QQmlApplicationEngine* engine)
{
    ::registerTypes();
    QQmlComponent* subWin = new QQmlComponent(engine, QUrl("qrc:/ReEngine.qml"));
    QQmlComponent* chiBtn = new QQmlComponent(engine, QUrl("qrc:/ReButton.qml"));
    QObject* objSubWin = subWin->create();
    QObject* objChiBtn = chiBtn->create();
    if (objSubWin && objChiBtn)
    {
        info = new PluginInfo{
                .m_name = "渲染页面",
                .m_subWin = dynamic_cast<QQmlComponent*>(objSubWin),
                .m_chiBtn = dynamic_cast<QQmlComponent*>(objChiBtn)
            };
    }
    else
    {
        if (subWin->isError())
            qCritical() << subWin->errorString().toStdString().data();
        if (chiBtn->isError())
            qCritical() << chiBtn->errorString().toStdString().data();
        info = nullptr;
    }
    return info;
}

